package LeetCode刷题;

import java.util.HashMap;

/**
 * @program: Java_Study
 * @author: Xiaofan
 * @createTime: 2021-09-28 14:41
 * @description: Functions of this class is
 *
 **/
public class 罗马数字转整数 {
    public static void main(String args[]){
        System.out.println(romanToInt("III"));
    }
    public static int romanToInt(String s) {
//        HashMap<Character,Integer> map=new HashMap();
//        map.put('I',1);
//        map.put('V',5);
//        map.put('X',10);
//        map.put('L',50);
//        map.put('C',100);
//        map.put('D',500);
//        map.put('M',1000);
        /**
         * 用Switch会比HashMap更快！
         */
        if(s.length()==1){
            return getValue(s.charAt(0));
        }
        int right=getValue(s.charAt(s.length()-1));
        int ans=right;
        for(int i=s.length()-2;i>=0;i--){
            int left=getValue(s.charAt(i));
            ans=(right<=left)?ans+left:ans-left;
            right=left;
        }
        return ans;
    }
    private static int getValue(char c){
        switch(c){
            case 'I':return 1;
            case 'V':return 5;
            case 'X':return 10;
            case 'L':return 50;
            case 'C':return 100;
            case 'D':return 500;
            case 'M':return 1000;
        }
        return 0;
    }
}